//index.js
import api from "../../utils/api.js";
import idcard from '../../utils/idcard.js'
import Toast from '@vant/weapp/toast/toast';
const app = getApp();

Page({
  data: {
    info: {
      contentAuthor: "",
      contentDatetime: '',
      contentDescription: '',
      contentDetails: '',
      contentDisplay: '0',
      contentSort: '0',
      scenes: [],
      scene: [],
      contentImgs: [],
      contentImg: {},
      contentSource: '',
      contentTitle: '',
      contentType: '',
      column: '',
      advantage:[],
    },
    columns: [
      { text: '智能产品', value: '1603944291762409473' },
      { text: '软件产品', value: '1603944116654411777' },
    ],
    type: '',
    categoryId: '',
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 190,
    keyboardHeight: 0,
    isIOS: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ categoryId: options.id, type: options.type })
    let title = '任务发布'
    if (options.type == 'news') {
      title = '新闻发布'
    } else if (options.type == 'product') {
      title = '产品发布'
    } else if (options.type == 'case') {
      title = '案例发布'
    } else if (options.type == 'business') {
      title = '业务合作'
    }
    wx.setNavigationBarTitle({
      title
    })
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({ value: null })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight - 600) : (windowHeight - 600)
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight 
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  },

  setValue: function (event) {
    let info = this.data.info
    const type = event.currentTarget.dataset.name
    info[type] = event.detail
    this.setData({ info })
  },
  uploadContentImg: function (e) {
    const { file } = e.detail;
    let _this = this
    let url = file[0].url

    wx.uploadFile({
      url: api.uploadPhoto,
      filePath: url,
      name: 'file',
      formData: {
        appId: 'false',
        rename: 'true',
        uploadPath: 'member',
      },
      success(res) {
        // 上传完成需要更新 fileList
        let info = _this.data.info
        info.contentImgs = file
        info.contentImg = res.data && JSON.parse(res.data).data
        console.log(info)
        _this.setData({ info })
      }
    })
  },

  deleteContentImage: function (e) {
    let info = this.data.info
    info.contentImgs = null
    info.contentImg = null
    this.setData({ info })
  },
  uploadImg: function (e) {
    const { file } = e.detail;
    let _this = this
    let url = file[0].url

    wx.uploadFile({
      url: api.uploadPhoto,
      filePath: url,
      name: 'file',
      formData: {
        appId: 'false',
        rename: 'true',
        uploadPath: 'member',
      },
      success(res) {
        // 上传完成需要更新 fileList
        let info = _this.data.info
        info.scenes.push(file[0])
        info.scene.push(res.data && JSON.parse(res.data).data)
        console.log(info)
        _this.setData({ info })
      }
    })
  },

  deleteImage: function (e) {
    let info = this.data.info
    info.scenes.splice(e.detail.index,1)
    info.scene.splice(e.detail.index,1)
    console.log(info)
    this.setData({ info })
  },
  onAdd:function(){
    let info = this.data.info
    const params = {
      title:'',
      description:'',
      imgs:[],
      img:[],
    }
    info.advantage.push(params)
    console.log(info)
    this.setData({ info })
  },
  onDelete:function(e){
    let info = this.data.info
    info.advantage.splice(e.currentTarget.dataset.index,1)
    this.setData({ info })
  },
  setProductValue:function(e){
    let info = this.data.info
    const index = e.currentTarget.dataset.index
    const name = e.currentTarget.dataset.name
    info.advantage[index][name] = e.detail
    this.setData({ info })
  },
  uploadProductAdvantagImg: function (e) {
    const { file } = e.detail;
    let _this = this
    let url = file[0].url
    const index = e.currentTarget.dataset.index

    wx.uploadFile({
      url: api.uploadPhoto,
      filePath: url,
      name: 'file',
      formData: {
        appId: 'false',
        rename: 'true',
        uploadPath: 'member',
      },
      success(res) {
        // 上传完成需要更新 fileList
        let info = _this.data.info
        info.advantage[index].imgs.push(file[0])
        info.advantage[index].img.push(res.data && JSON.parse(res.data).data)
        console.log(info)
        _this.setData({ info })
      }
    })
  },

  deleteProductAdvantagImage: function (e) {
    let info = this.data.info
    const index = e.currentTarget.dataset.index
    console.log(e)
    console.log(info)
    info.advantage[index].imgs.splice(e.detail.index,1)
    info.advantage[index].img.splice(e.detail.index,1)
    console.log(info)
    this.setData({ info })
  },
  getHtml: function (e) {
    let info = this.data.info
    info.contentDetails = e.detail.html
    this.setData({ info })
  },
  setShowPicker: function (e) {
    const showPicker = e.currentTarget.dataset.flag == '1' ? true : false
    this.setData({ showPicker });
  },
  onConfirmPick: function (e) {
    let categoryId = e.detail.value.value
    let info = this.data.info
    info.column = e.detail.value.text
    this.setData({ showPicker: false, categoryId, info });
  },

  onSubmit: function (event) {
    const { info, type, categoryId } = this.data
    delete info.contentImgs
    delete info.scenes
    delete info.column
    if (type == 'product' && !categoryId) {
      return Toast({
        message: "请选择栏目",
        duration: 1500
      });
    }
    if(type === 'product'){
      info.advantage && info.advantage.length && info.advantage.map(item=>{
        delete item.imgs
      })
    }else{
      delete info.advantage
      delete info.scenes
    }
    var myDate = new Date();
    let month = myDate.getMonth() + 1
    if (month < 10) {
      month = "0" + month
    }
    let minutes = myDate.getMinutes()
    if (minutes < 10) {
      minutes = "0" + minutes
    }
    let seconds = myDate.getSeconds()
    if (seconds < 10) {
      seconds = "0" + seconds
    }
    info.contentDatetime = myDate.getFullYear() + '-' + month + '-' + myDate.getDate() + ' ' + myDate.getHours() + ':' + minutes + ':' + seconds
    info.categoryId = categoryId
    console.log(info)
    wx.request({
      url: api.saveContent,
      method: "POST",
      data: info,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success(res) {
        //更改备注成功回调函数
        if (res.data.code == 200) {
          Toast({
            type: 'success',
            message: "发布成功",
            duration: 1500,
            onClose: () => {
              wx.navigateBack({
                delta: 1
              });
            },
          })
        }
      },
      fail(res) {
        //更改备注失败回调函数
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

});
